<template>
    <view class="content">
        <view class="text-area">
            <text class="zoom-text">照片条预览</text>
        </view>
        <view class="footer">
            <button class="confirm-btn" @click="downloadPhotoStrip">
                下载照片条
            </button>
        </view>
    </view>
    <view class="box">
        <view class="ptoBox" :style="{ backgroundColor: photoStripColor }" id="photoStrip">
            <view class="photo-grid">
                <view class="grid-item" v-for="(item, index) in 4" :key="index" :style="{ position: 'relative' }">
                    <view class="image-container">
                        <image v-if="previewImages[index]" class="preview-image" :src="previewImages[index]"
                            style="width: 100%; height: 100%;object-fit: cover;" mode="aspectFill" />
                        <text v-else class="image-placeholder"></text>
                    </view>
                </view>
                <view class="bottom" :style="{ color: textColor }">
                    {{ 'Snapora ' + CurTime() }}
                </view>
            </view>
            <!-- 贴纸渲染区域 - 覆盖整个照片条 -->
            <template v-for="sticker in currentStickers" :key="sticker.id">
                <image class="sticker-item" :src="sticker.content" :style="sticker.style" mode="scaleToFill" />
            </template>

        </view>
        <view class="btnBox">
            <view class="title">
                照片条背景色
            </view>
            <view class="row" v-for="(row, rowIndex) in buttonRows" :key="rowIndex">
                <button v-for="(btn, btnIndex) in row" :key="btnIndex" class="custom-btn" @click="handleClick(btn.color)">
                    {{ btn.text }}
                </button>
            </view>
            <view class="title" style="margin-top: 40rpx;">
                贴纸主题
            </view>
            <view class="row" v-for="(row, rowIndex) in stickerThemeRows" :key="'sticker-row-' + rowIndex">
                <button v-for="(btn, btnIndex) in row" :key="'sticker-btn-' + btnIndex" class="custom-btn"
                    @click="applyStickerTheme(btn.themeKey)">
                    {{ btn.text }}
                </button>
            </view>
        </view>
    </view>

    <!-- 隐藏的Canvas用于生成图片 -->
    <canvas canvas-id="photoStripCanvas" id="photoStripCanvas"
        style="width: 350px; height: 1450px; position: absolute; left: -9999px; top: -9999px;"></canvas>
</template>

<script setup>
import { onLoad, onReady } from '@dcloudio/uni-app'
import { ref, reactive, computed, getCurrentInstance } from 'vue'
const ptoNum = ref('')
const photoStripColor = ref('#ffffff')
const textColor = ref('#000000')
// const nowTime = CurTime()
const buttonRows = reactive([
    [
        { text: '白色', color: '#ffffff' },
        { text: '蓝色', color: '#b8dde9' }
    ],
    [
        { text: '粉色', color: '#f6d5da' },
        { text: '绿色', color: '#dde6d5' }
    ],
    [
        { text: '黄色', color: '#fff2cc' },
        { text: '蔷薇色', color: '#ceaeaf' }
    ],
    [
        { text: '黑色', color: '#000000' },
        { text: '灰色', color: '#808080' }
    ],
    [
        { text: '可可蛋奶', color: '#ebe3d6' },
        { text: '香盈藕粉', color: '#e6d5cd' }
    ],
    [
        { text: '蜜合色', color: '#faeee0' },
        { text: '浮冰', color: '#d7e4ea' }
    ]
])

const previewImages = ref([])
// console.log('aaaaaa', globalData.photos)
onLoad((options) => {
    const { globalData } = getApp()
    previewImages.value = globalData.photos || []

    if (options.type && options.images) {
        ptoNum.value = {
            four: '四',
        }[options.type] || '未知'
    }
})

// 模版背景色和字体颜色
const handleClick = (color) => {
    photoStripColor.value = color
    if (color === '#000000') {
        textColor.value = '#ffffff'
    } else {
        textColor.value = '#000000'
    }
}

const currentStickerTheme = ref('')
// 贴纸主题配置 - 全部改为整张图片覆盖
const stickerThemes = reactive({
    noSticker: {
        name: '无贴纸',
        stickers: [
            {
                content: '',
            },
        ]
    },
    nature: {
        name: '粉色小熊',
        stickers: [
            {
                content: '/static/8.png',
            },
        ]
    },
    cheery: {
        name: '车厘子',
        stickers: [
            {
                content: '/static/9.png',
            },
        ]
    },

})

// 贴纸主题按钮配置
const stickerThemeRows = reactive([
    [
        { text: '无贴纸', themeKey: 'noSticker' },
    ],
    [
        { text: '粉色小熊', themeKey: 'nature' },
        { text: '车厘子', themeKey: 'cheery' }
    ],

])

// 当前贴纸列表
const currentStickers = ref([])

// 应用主题方法
const applyStickerTheme = (themeKey) => {
    currentStickerTheme.value = themeKey
    currentStickers.value = stickerThemes[themeKey].stickers.map((sticker, index) => ({
        ...sticker,
        id: `${themeKey}-${index}-${Date.now()}`
    }))
}
// 时间组件
const CurTime = () => {
    const now = new Date();

    // 获取年、月、日
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需加1
    const day = String(now.getDate()).padStart(2, '0');

    // 获取小时、分钟
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');

    // 拼接成xxxx/xx/xx xx:xx格式
    return `${year}/${month}/${day} ${hours}:${minutes}`;
}
// console.log('xxxxxxzzz', CurTime())

// 下载照片条功能
const downloadPhotoStrip = async () => {
    try {
        uni.showLoading({ title: '生成照片条中...' })

        // 获取Canvas上下文
        const ctx = uni.createCanvasContext('photoStripCanvas')

        // 获取设备像素比，确保图片清晰
        const dpr = uni.getSystemInfoSync().pixelRatio || 1

        // 设置Canvas尺寸（单位：px）
        const canvasWidth = 350
        const canvasHeight = 1450

        // 圆角半径
        const borderRadius = 12

        // 绘制背景
        ctx.fillStyle = photoStripColor.value
        ctx.fillRect(0, 0, canvasWidth, canvasHeight)

        // 绘制圆角矩形的辅助函数
        const drawRoundedRect = (x, y, width, height, radius, fillColor) => {
            ctx.beginPath();
            // 左上角
            ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5);
            // 右上角
            ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2);
            // 右下角
            ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5);
            // 左下角
            ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI);
            ctx.closePath();

            if (fillColor) {
                ctx.fillStyle = fillColor;
            }
            ctx.fill();
        }

        // 计算每个格子的位置和尺寸
        const gridWidth = 282 // 350 - 60 (左右padding)
        const gridHeight = 270
        const gridPositions = [
            { top: 80 },    // 第一个格子：58(padding) + 20(margin-top)
            { top: 390 },   // 第二个格子：78 + 270 + 40
            { top: 700 },   // 第三个格子：388 + 270 + 40
            { top: 1000 }   // 第四个格子：698 + 270 + 40
        ]

        // 绘制四个格子中的图片
        for (let i = 0; i < 4; i++) {
            if (previewImages.value[i]) {
                try {
                    // 先绘制带圆角的背景（作为图片的容器）
                    const imgX = 35 // 左侧padding
                    const imgY = gridPositions[i].top

                    drawRoundedRect(imgX, imgY, gridWidth, gridHeight, borderRadius, '#f5f5f5')

                    // 获取图片信息
                    const imgInfo = await uni.getImageInfo({ src: previewImages.value[i] })
                    // 计算宽高比
                    const sourceRatio = imgInfo.width / imgInfo.height
                    const targetRatio = gridWidth / gridHeight

                    let sx = 0, sy = 0, sWidth = imgInfo.width, sHeight = imgInfo.height


                    if (sourceRatio > targetRatio) {
                        // 图片比目标区域更宽 - 裁剪左右两侧
                        sHeight = imgInfo.height
                        sWidth = sHeight * targetRatio
                        sx = (imgInfo.width - sWidth) / 2
                    } else if (sourceRatio < targetRatio) {
                        // 图片比目标区域更高 - 裁剪上下两侧
                        sWidth = imgInfo.width
                        sHeight = sWidth / targetRatio
                        sy = (imgInfo.height - sHeight) / 2
                    }

                    // 绘制图片（cover模式）
                    // 先保存当前状态
                    ctx.save()
                    // 创建圆角矩形路径作为裁剪区域
                    drawRoundedRect(imgX, imgY, gridWidth, gridHeight, borderRadius)
                    ctx.clip() // 设置裁剪区域

                    // 在裁剪区域内绘制图片
                    console.log('当前 gridWidth 的值：', gridWidth, gridHeight);
                    ctx.drawImage(
                        imgInfo.path,
                        sx, sy, sWidth, sHeight,    // 源图片裁剪区域（动态计算）
                        imgX, imgY, gridWidth, gridHeight // 目标绘制区域
                    )
                    console.log('gridWidth', gridWidth, gridHeight)

                    // 恢复状态，取消裁剪
                    ctx.restore()

                } catch (e) {
                    console.error(`加载图片 ${i} 失败:`, e)
                    // 绘制带圆角的占位符
                    drawRoundedRect(35, gridPositions[i].top, gridWidth, gridHeight, borderRadius, '#f5f5f5')
                    ctx.fillStyle = '#999'
                    ctx.font = '16px Arial'
                    ctx.textAlign = 'center'
                    ctx.fillText(` `, 35 + gridWidth / 2, gridPositions[i].top + gridHeight / 2)
                }
            } else {
                // 绘制带圆角的占位符
                drawRoundedRect(35, gridPositions[i].top, gridWidth, gridHeight, borderRadius, '#f5f5f5')
                ctx.fillStyle = '#999'
                ctx.font = '16px Arial'
                ctx.textAlign = 'center'
                ctx.fillText(` `, 35 + gridWidth / 2, gridPositions[i].top + gridHeight / 2)
            }
        }

        // 绘制贴纸 - 整张图片覆盖
        for (const sticker of currentStickers.value) {
            try {
                // 处理本地图片路径
                let stickerPath = sticker.content

                // 绘制整张贴纸图片覆盖整个照片条
                ctx.drawImage(
                    stickerPath,
                    0, 0, canvasWidth, canvasHeight
                )
            } catch (e) {
                console.error('加载贴纸图片失败:', e)
                // 绘制占位符
                ctx.fillStyle = 'rgba(255, 0, 0, 0.3)'
                ctx.fillRect(0, 0, canvasWidth, canvasHeight)
            }
        }

        // 绘制底部文字
        ctx.fillStyle = textColor.value
        ctx.font = '22px Arial'
        ctx.textAlign = 'center'
        ctx.fillText('Snapora ' + CurTime(), canvasWidth / 2, canvasHeight - 60) // 距离底部30px

        // 将绘制内容渲染到Canvas
        ctx.draw(false, () => {
            // 生成临时图片
            uni.canvasToTempFilePath({
                canvasId: 'photoStripCanvas',
                destWidth: canvasWidth * dpr,
                destHeight: canvasHeight * dpr,
                success: (res) => {
                    // 保存图片到相册
                    uni.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: () => {
                            uni.hideLoading()
                            uni.showToast({ title: '照片条已保存', icon: 'success' })
                        },
                        fail: (err) => {
                            uni.hideLoading()
                            console.error('保存图片失败:', err)
                            uni.showToast({ title: '保存失败', icon: 'none' })
                        }
                    })
                },
                fail: (err) => {
                    uni.hideLoading()
                    console.error('生成图片失败:', err)
                    uni.showToast({ title: '生成失败', icon: 'none' })
                }
            })
        })
    } catch (error) {
        uni.hideLoading()
        console.error('下载照片条失败:', error)
        uni.showToast({ title: '下载失败', icon: 'none' })
    }
}

</script>

<style lang="scss">
.content {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.text-area {
    display: flex;
    justify-content: center;
}

.zoom-text {
    margin-top: 50rpx;
    font-weight: bolder;
    font-size: 76rpx;
    color: #333;
    animation: zoom 2s ease-in-out infinite;
}

@keyframes zoom {

    0%,
    100% {
        transform: scale(0.7);
    }

    50% {
        transform: scale(0.8);
    }
}

.box {
    display: flex;
}

.title {
    display: flex;
    justify-content: center;
    font-size: 32rpx;
    margin-bottom: 30rpx;
    color: black;
}

.ptoBox {
    margin-top: 50rpx;
    margin-left: 30rpx;
    margin-bottom: 100rpx;
    width: 350rpx;
    height: 1450rpx;
    background-color: white;
    border-radius: 20rpx;
    padding: 28rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    position: relative;
    /* 添加相对定位，使贴纸可以相对于此容器定位 */
}

.image-container {
    width: 100%;
    height: 100%;
    position: relative;
    border-radius: 16rpx;
    overflow: hidden;
}

.photo-grid {
    margin-left: 7.7rpx;
    // margin-right: 12rpx;
}

.preview-image {
    width: 100%;
    height: 100%;
}

.image-placeholder {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #999;
}

.grid-item {
    width: 282rpx;
    height: 270rpx;
    // margin-top: 38rpx;
    // margin-bottom: 30rpx;
    background: #f5f5f5;
    border-radius: 16rpx;
    overflow: hidden;
}

/* 单独设置第一个格子的样式 */
.grid-item:first-child {
    /* 这里写第一个格子的专属样式，例如： */
    // background-color: #a07171;
    /* 示例：红色背景 */
    // border: 2rpx solid #000;
    margin-top: 70rpx;
    /* 示例：黑色边框 */
    /* 可以覆盖上面的任意属性 */
}

.grid-item:not(:first-child) {
    // background: #e8e8e8;
    // border: 2rpx solid #ddd;
    margin-top: 26rpx;

}


.bottom {
    display: flex;
    justify-content: center;
    font-size: 22rpx;
    margin-top: 80rpx;
    z-index: 2;
    /* 确保文字在贴纸上方 */
}

.btnBox {
    margin-top: 50rpx;
    margin-left: 30rpx;
    width: 300rpx;
    height: 800rpx;
}

.row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
}

.custom-btn {
    width: 120rpx !important;
    height: 60rpx !important;
    line-height: 60rpx !important;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    border-radius: 50rpx;
    border: 6rpx solid #000;
    font-size: 24rpx;
    font-weight: bold;
    background: transparent;
}

.custom-btn:active {
    opacity: 0.8;
    transform: scale(0.98);
}

.sticker-item {
    pointer-events: none;
    user-select: none;
    position: absolute;
    /* 确保贴纸绝对定位 */
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1;
    /* 确保贴纸在照片上方但文字下方 */
}

.confirm-btn {
    width: 300rpx;
    height: 80rpx;
    line-height: 60rpx;
    position: relative;
    margin-top: 30rpx;
    left: auto;
    transform: none;
    background: transparent !important;
    border: 6rpx solid black;
    border-radius: 50rpx;
    color: black;
    font-size: 28rpx;
    box-shadow: none;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
}

.confirm-btn:active {
    transform: scale(0.95);
}
</style>